import {io} from 'socket.io-client'

const socketMap = new Map()

export default function createWebSocket(namespace = '') {
  let socket = socketMap.get(namespace)
  if (socket) {
    return socket
  }
  socket = io('http://localhost:9001' + namespace)
  socket.on('connection', () => {
    console.log('连接成功...')
  })
  socketMap.set(namespace, socket)
  return socket
}

/**
 * 关闭socket连接
 * 如果传入 namespace 则关闭指定的socket，否则关闭所有的socket
 * @param namespace
 */
export function close(namespace) {
  for (const [nsp, socket] of socketMap.entries()) {
    if (namespace === undefined || nsp === namespace) {
      socket.close()
    }
  }
}
